import i18n from "@/lang";
// Parse the time to string
export const parseTime = (
  time?: object | string | number | null,
  dateTime?: boolean,
  cFormat?: string
): string | null => {
  if (time === undefined || !time) {
    return null
  }
  const format = cFormat || (dateTime ? '{y}-{m}-{d}' : '{y}-{m}-{d} {h}:{i}:{s}')
  let date: Date
  if (typeof time === 'object') {
    date = time as Date
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: { [key: string]: number } = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return timeStr
}

export const transformTimestamp = (timestamp: any) => {
  let a = new Date(timestamp).getTime();
    const date = new Date(a);
    const Y = date.getFullYear() + '-';
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    const D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + '  ';
    const h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
    const m = (date.getMinutes() <10 ? '0'+date.getMinutes() : date.getMinutes()) ;
    // const s = date.getSeconds(); // 秒
    const dateString = Y + M + D + h + m;
    // console.log('dateString', dateString); // > dateString 2021-07-06 14:23
    return dateString;
}

// Format and filter json data using filterKeys array
export const formatJson = (filterKeys: any, jsonData: any) =>
  jsonData.map((data: any) => filterKeys.map((key: string) => {
    if (key === 'timestamp') {
      return parseTime(data[key])
    } else {
      return data[key]
    }
  }))

// Check if an element has a class
export const hasClass = (ele: HTMLElement, className: string) => {
  return !!ele.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}

// Add class to element
export const addClass = (ele: HTMLElement, className: string) => {
  if (!hasClass(ele, className)) ele.className += ' ' + className
}

// Remove class from element
export const removeClass = (ele: HTMLElement, className: string) => {
  if (hasClass(ele, className)) {
    const reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

// Toggle class for the selected element
export const toggleClass = (ele: HTMLElement, className: string) => {
  if (!ele || !className) {
    return
  }
  let classString = ele.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  ele.className = classString
}

export function debounce(...args: any) {
  return require("lodash").debounce(...args);
}

/**
 * 多位数补零
 * @param digit 位数
 * @param num 原值
 */
export function unitNumberWithZero(digit: number, num: number) {
  let beforeStr = "";

  if (num === 0) {
    for (let i = 0; i < digit - 1; i++) {
      beforeStr += "0";
    }
  } else {
    for (let i = 0; i < digit; i++) {
      if (num / Math.pow(10, i) < 1) {
        beforeStr += "0";
      }
    }
  }

  return beforeStr + num;
}

/**
 * 允许登录时间短数据转换方法
 */
export function loginTimeslotToString(timeslot: any) {
  const start = timeslot.start;
  const end = timeslot.end;
  const startHour = Math.floor(start / 60);
  const startMinute = Math.floor(start % 60);

  const endHour = Math.floor(end / 60);
  const endMinute = Math.floor(end % 60);

  return unitNumberWithZero(2, startHour) + " : " + unitNumberWithZero(2, startMinute) + " - " + unitNumberWithZero(2, endHour) + " : " + unitNumberWithZero(2, endMinute);
}

/**
 * 格式化秒数，转换为天时分秒
 * @param value 秒数
 */
export function formatSeconds(value: any) {
  let theTime: any = parseInt(value);// 需要转换的时间秒s
  let minute: any;// 分
  let hour: any;// 小时
  let day: any;// 天
  if (theTime > 60) {
    minute = parseInt((theTime / 60) + "");
    theTime = parseInt((theTime % 60) + "");
    if (minute > 60) {
      hour = parseInt((minute / 60) + "");
      minute = parseInt((minute % 60) + "");
      if (hour > 24) {
        // 大于24小时
        day = parseInt((hour / 24) + "");
        hour = parseInt((hour % 24) + "");
      }
    }
  }
  let result = '';
  if (theTime >= 0) {
    result = "" + parseInt(theTime) + i18n.t('common.second');
  }
  if (minute > 0) {
    result = "" + parseInt(minute) + i18n.t('common.minutes') + result;
  }
  if (hour > 0) {
    result = "" + parseInt(hour) + i18n.t('common.hour') + result;
  }
  if (day > 0) {
    result = "" + parseInt(day) + i18n.t('common.day') + result;
  }
  return result;
}

// 字节格式化
export function bytesToSize(bytes: any) {
  if (bytes === 0) {
    return "0B";
  }
  const k = 1024;
  const size = ['B', 'KB', 'MB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  const num = bytes / Math.pow(k, i);
  return num.toPrecision(3) + '' + size[i];
}

export function randomPasswordString() {
  const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  const lowLetters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  const capLetters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  const specialChars = ['.', '*'];

  const firstChars = [
    nums[parseInt((Math.random() * nums.length).toString())],
    nums[parseInt((Math.random() * nums.length).toString())],
    lowLetters[parseInt((Math.random() * lowLetters.length).toString())],
    lowLetters[parseInt((Math.random() * lowLetters.length).toString())],
    capLetters[parseInt((Math.random() * capLetters.length).toString())],
    capLetters[parseInt((Math.random() * capLetters.length).toString())],
    specialChars[parseInt((Math.random() * specialChars.length).toString())],
    specialChars[parseInt((Math.random() * specialChars.length).toString())]
  ]

  firstChars.sort(() => (Math.random() - Math.random()));

  return firstChars.join("");
}

// 深拷贝
export function deepClone(obj: any){
  let objClone: any = Array.isArray(obj)?[]:{};
  if(obj && typeof obj==="object"){
      for(let key in obj){
          if(obj.hasOwnProperty(key)){
              //判断ojb子元素是否为对象，如果是，递归复制
              if(obj[key]&&typeof obj[key] ==="object"){
                  objClone[key] = deepClone(obj[key]);
              }else{
                  //如果不是，简单复制
                  objClone[key] = obj[key];
              }
          }
      }
  }
  return objClone;
}

/**
* 系统管理员 有工作区名称就展示 没有就展示-
* 租户管理员 有非虚拟工作区名称就展示 没有就展示-
*/
export function getWorkareaName(row: any) {
 if (process.env.VUE_APP_AUTH_RULE === "system_admin") {
   if (row.workarea_name) return row.workarea_name;
 } else if (process.env.VUE_APP_AUTH_RULE === "tenant_admin") {
   if (row.workarea_name && row.composite_specification === "0") return row.workarea_name;
 }
 return "-"
}

/**
 * 脱敏
 * 前三后四中间加密
 */
export function desensitization(word: string) {
  const before = word.slice(0, 3);
  const after = word.slice(-4);
  const mask = new Array(5).join("*");

  return before + mask + after;
}
